<template>
  <view class="antenna-device-page page-content">
    <z-paging ref="paging" v-model="currentList" @query="queryList" :auto="false" :refresher-enabled="true"
      :loading-more-enabled="true" empty-view-text="暂无数据">
      <template #top>
        <up-navbar title="ETC天线设备列表" :autoBack="false" :fixed="true" bgColor="transparent" :border="false" placeholder
          @leftClick="handleBackClick">
          <template #right>
            <view @click="handleAdd">新增设备</view>
          </template>
        </up-navbar>

        <up-sticky class="padding-20" bgColor="transparent">
          <!-- 统计卡片 -->
          <view class="stats-cards">
            <view class="stats-card">
              <view class="card-title">总设备数</view>
              <view class="card-value">{{ deviceStats.totalDevices }}</view>
              <view class="card-unit">台</view>
            </view>
            <view class="stats-card">
              <view class="card-title">离线设备</view>
              <view class="card-value">{{ deviceStats.offlineDevices }}</view>
              <view class="card-unit">台</view>
            </view>
          </view>

          <!-- 筛选区域 -->
          <view class="header-bar">
            <view class="header-bar-location" @click="showAreaPicker = true">
              <text class="title">设备区域</text>
              <up-icon name="arrow-down"></up-icon>
            </view>
            <view class="header-bar-status" @click="showStatusPicker = true">
              <text class="title">联网状态</text>
              <up-icon name="arrow-down"></up-icon>
            </view>
          </view>

          <!-- 区域选择器 -->
          <up-picker :show="showAreaPicker" :columns="areaColumns" :closeOnClickOverlay="true"
            @confirm="handleAreaConfirm" @cancel="showAreaPicker = false"
            @close="showAreaPicker = false"></up-picker>

          <!-- 状态选择器 -->
          <up-picker :show="showStatusPicker" :columns="statusColumns" :closeOnClickOverlay="true"
            @confirm="handleStatusConfirm" @cancel="showStatusPicker = false"
            @close="showStatusPicker = false"></up-picker>

          <up-search v-model="searchKeyword" :clearabled="true" :showAction="false" placeholder="请输入设备SN码"
            @search="handleSearch"></up-search>
        </up-sticky>
      </template>

      <view class="antenna-device-list">
        <view class="list-item-card" v-for="(item, index) in currentList" :key="index">
          <view class="card-header">
            <view class="title">
              设备SN码：<text class="number">{{ item.serialNo }}</text>
            </view>
            <view class="status" :class="item.status === '1' ? 'online' : 'offline'">
              {{ item.status === '1' ? '在线' : '离线' }}
            </view>
          </view>
          <view class="card-content-box">
            <view class="content">
              <view class="item">
                <text class="label">
                  设备厂商：
                </text>
                <text class="value">
                  {{ item.manufacturer }}
                </text>
              </view>
              <view class="item">
                <text class="label">
                  所属区域：
                </text>
                <text class="value">
                  {{ item.area }}
                </text>
              </view>
              <view class="item">
                <text class="label">
                  最近心跳：
                </text>
                <text class="value">
                  {{ item.lastHeartbeat }}
                </text>
              </view>
              <view class="item">
                <text class="label">
                  安装位置：
                </text>
                <text class="value">
                  {{ item.location }}
                </text>
              </view>
            </view>
            <view class="card-footer">
              <view class="operate">
                <up-button type="primary" text="编辑" size="mini" class="custom-style" @click="handleEdit(item)"></up-button>
                <up-button type="warning" :text="item.disabled ? '启用' : '禁用'" size="mini" class="custom-style" @click="handleToggleStatus(item)"></up-button>
                <up-button type="error" text="删除" size="mini" class="custom-style" @click="handleDelete(item)"></up-button>
              </view>
            </view>
          </view>
        </view>
      </view>
    </z-paging>

    <AntennaModal v-model:show="show" :type="type" :row-data="editingData" @refresh="refreshList" />
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';

// 引入模态框组件
import AntennaModal from '../../base-manage/components/AntennaModal.vue';

// 模态框控制
const type = ref('add');
const show = ref(false);
const editingData = ref<any>(null);

// 搜索和筛选
const searchKeyword = ref('');
const showAreaPicker = ref(false);
const showStatusPicker = ref(false);
const selectedArea = ref('');
const selectedStatus = ref('');

// 区域和状态选择器数据
const areaColumns = reactive([
  ['全部区域', '大良镇', '顺德佛山', '容桂镇', '杏坛镇', '伦教街道', '勒流镇', '陈村镇', '均安镇'],
]);

const statusColumns = reactive([
  ['全部状态', '在线', '离线'],
]);

// 设备统计数据
const deviceStats = reactive({
  totalDevices: 0,
  offlineDevices: 0
});

// z-paging 组件引用
const paging = ref(null);

// 当前显示的列表数据
const currentList = ref([]);

// 处理返回点击事件
const handleBackClick = () => {
  uni.redirectTo({
    url: '/pages/base-manage/devices/index'
  });
};

// 处理区域选择确认
const handleAreaConfirm = (e) => {
  selectedArea.value = e.value[0] === '全部区域' ? '' : e.value[0];
  showAreaPicker.value = false;
  refreshList();
};

// 处理状态选择确认
const handleStatusConfirm = (e) => {
  const statusMap = {
    '在线': '1',
    '离线': '0',
    '全部状态': ''
  };
  selectedStatus.value = statusMap[e.value[0]];
  showStatusPicker.value = false;
  refreshList();
};

// 刷新列表
const refreshList = () => {
  paging.value.reload();
};

// 处理搜索
const handleSearch = () => {
  refreshList();
};

// 获取设备列表数据
const queryList = async (pageNo, pageSize) => {
  console.log('查询参数:', pageNo, pageSize, searchKeyword.value, selectedArea.value, selectedStatus.value);

  const params = {
    pageNum: pageNo,
    pageSize,
    keyword: searchKeyword.value,
    area: selectedArea.value,
    status: selectedStatus.value
  };

  await fetchList(params);
};

// 模拟获取列表数据
const fetchList = async (params) => {
  try {
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 500));
    
    // 模拟数据
    const mockData = generateMockData(params);
    
    // 更新统计数据
    deviceStats.totalDevices = mockData.total;
    deviceStats.offlineDevices = mockData.records.filter(item => item.status === '0').length;
    
    // 更新列表数据
    paging.value.complete(mockData.records);
  } catch (error) {
    console.error('获取数据失败', error);
    paging.value.complete(false);
  }
};

// 生成模拟数据
const generateMockData = (params) => {
  const { pageNum, pageSize, keyword, area, status } = params;
  
  // 基础数据集
  let records = [];
  const areas = ['大良镇', '顺德佛山', '容桂镇', '杏坛镇', '伦教街道', '勒流镇', '陈村镇', '均安镇'];
  const manufacturers = ['杭州海康', '深圳华为', '北京中电', '上海大华', '广州智能'];
  
  // 生成30条模拟数据
  for (let i = 1; i <= 30; i++) {
    const serialNo = `ETC${String(i).padStart(6, '0')}`;
    const deviceStatus = Math.random() > 0.3 ? '1' : '0'; // 70%概率在线
    const deviceArea = areas[Math.floor(Math.random() * areas.length)];
    const deviceManufacturer = manufacturers[Math.floor(Math.random() * manufacturers.length)];
    
    records.push({
      id: i.toString(),
      serialNo,
      manufacturer: deviceManufacturer,
      area: deviceArea,
      status: deviceStatus,
      lastHeartbeat: deviceStatus === '1' ? 
        `${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()}` : 
        `${new Date(Date.now() - Math.random() * 86400000 * 7).toLocaleDateString()} ${new Date().toLocaleTimeString()}`,
      location: `${deviceArea}停车场${Math.floor(Math.random() * 10) + 1}号入口`,
      disabled: Math.random() > 0.9 // 10%概率被禁用
    });
  }
  
  // 应用筛选条件
  if (keyword) {
    records = records.filter(item => item.serialNo.includes(keyword));
  }
  
  if (area) {
    records = records.filter(item => item.area === area);
  }
  
  if (status) {
    records = records.filter(item => item.status === status);
  }
  
  // 分页处理
  const total = records.length;
  const start = (pageNum - 1) * pageSize;
  const end = start + pageSize;
  records = records.slice(start, end);
  
  return {
    records,
    total,
    pages: Math.ceil(total / pageSize),
    current: pageNum
  };
};

// 处理添加设备
const handleAdd = () => {
  type.value = 'add';
  editingData.value = null;
  show.value = true;
};

// 处理编辑设备
const handleEdit = (item) => {
  type.value = 'edit';
  editingData.value = { ...item };
  show.value = true;
};

// 处理删除设备
const handleDelete = (item) => {
  uni.showModal({
    title: '提示',
    content: `确定要删除设备 ${item.serialNo} 吗？`,
    success: (res) => {
      if (res.confirm) {
        // 模拟删除操作
        uni.showToast({
          title: '删除成功',
          icon: 'success'
        });
        refreshList();
      }
    }
  });
};

// 处理启用/禁用设备
const handleToggleStatus = (item) => {
  const action = item.disabled ? '启用' : '禁用';
  uni.showModal({
    title: '提示',
    content: `确定要${action}设备 ${item.serialNo} 吗？`,
    success: (res) => {
      if (res.confirm) {
        // 模拟操作
        uni.showToast({
          title: `${action}成功`,
          icon: 'success'
        });
        refreshList();
      }
    }
  });
};

// 页面挂载时获取数据
onMounted(() => {
  refreshList();
});
</script>

<style scoped lang="scss">
.antenna-device-page {
  background-color: #f5f5f5;
}

.padding-20 {
  padding: 20rpx;
}

.stats-cards {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20rpx;
  
  .stats-card {
    flex: 1;
    background-color: #ffffff;
    border-radius: 12rpx;
    padding: 20rpx;
    margin: 0 10rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    text-align: center;
    
    &:first-child {
      margin-left: 0;
    }
    
    &:last-child {
      margin-right: 0;
    }
    
    .card-title {
      font-size: 24rpx;
      color: #666;
      margin-bottom: 10rpx;
    }
    
    .card-value {
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
      display: inline-block;
    }
    
    .card-unit {
      font-size: 24rpx;
      color: #666;
      display: inline-block;
      margin-left: 4rpx;
    }
  }
}

.header-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0rpx 20rpx 30rpx;

  &-location, &-status {
    display: flex;
    align-items: center;
    background-color: #ffffff;
    padding: 10rpx 20rpx;
    border-radius: 8rpx;

    .title {
      font-size: 28rpx;
      color: #333;
      margin-right: 10rpx;
    }
  }
}

.antenna-device-list {
  padding: 20rpx;
}

.list-item-card {
  background-color: #ffffff;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx;
    border-bottom: 1rpx solid #f0f0f0;

    .title {
      font-size: 28rpx;
      color: #333;

      .number {
        font-weight: bold;
      }
    }

    .status {
      font-size: 24rpx;
      padding: 4rpx 16rpx;
      border-radius: 20rpx;

      &.online {
        background-color: rgba(25, 190, 107, 0.1);
        color: #19be6b;
      }

      &.offline {
        background-color: rgba(255, 69, 0, 0.1);
        color: #ff4500;
      }
    }
  }

  .card-content-box {
    padding: 20rpx;

    .content {
      .item {
        display: flex;
        margin-bottom: 16rpx;

        .label {
          width: 180rpx;
          font-size: 26rpx;
          color: #666;
        }

        .value {
          flex: 1;
          font-size: 26rpx;
          color: #333;
        }
      }
    }

    .card-footer {
      display: flex;
      justify-content: flex-end;
      margin-top: 20rpx;
      padding-top: 20rpx;
      border-top: 1rpx solid #f0f0f0;

      .operate {
        display: flex;
        gap: 20rpx;

        .custom-style {
          margin: 0 5rpx;
        }
      }
    }
  }
}
</style>